<?php
/**
 * 在线问题系统
 * User: Mark
 * Time: 12-11-23 上午9:04
 */
class Live
{
	/** @var \db_mysqli  */
	private $_db;

	/** @var 主数据表 */
	private $_table;

	/** @var 关系表 */
	private $_tableRel;

	/** @var 关键词表 */
	private $_tableKw;

	/** @var 会员模式 */
	private $_modes;

	const RETURN_TYPE_ARRAY = 'ARRAY';
	const RETURN_TYPE_JSON  = 'JSON';

	/** 初始化数据表和数据链接 */
	public function __construct()
	{
		global $db;
		$this->_db       = $db;
		$this->_table    = $db->getPre() . 'qs_answer';
		$this->_tableRel = $db->getPre() . 'qs_relation';
		$this->_tableKw  = $db->getPre() . 'qs_keyword';
		$this->_modes    = $this->_getModes();
	}

	/**
	 * 获取所有的服务商分类
	 */
	private function _getModes()
	{
		$cats = get_maincat(3836, 25);
		return $cats;
	}

	/**
	 * 公司的分类
	 * @return multitype
	 */
	public function comCate()
	{
		return $this->_modes;
	}

	/**
	 * 服务商查询
	 * @param     $areaid
	 * @param int $modeid
	 * @return string
	 */
	public function servicerSearch($areaid, $catid = 0, $type = self::RETURN_TYPE_ARRAY)
	{
		global $db, $AREA;
		$condition = '';
		$return    = array();
		if ($areaid != 0) {
			if ($AREA[$areaid]['arrchildid']) {
				$condition .= " and d.company_areaid in ({$AREA[$areaid]['arrchildid']})";
			} else {
				$condition .= " and d.company_areaid = {$areaid}";
			}
		}

		$category = PCache::read('category-25.php');
		if(isset($catid) && $catid!=''){
			if($category[$catid]['arrchildid']){
				$categoryid = $category[$catid]['arrchildid'];
				$condition .= " AND c.catid IN($categoryid)";
			}else{
				$condition .= " AND c.catid IN($catid)";
			}
		}else{
			$categoryid = $category[3836]['arrchildid'];
			$condition .= " AND c.catid IN($categoryid)";
		}

		$table = Table::name(Table::NAME_MERCHANT_DOC);
		$tableCatid = Table::name(Table::NAME_MERCHANT_CATID);
		$sql = "SELECT distinct(d.did),d.title from $table d,$tableCatid c where d.did=c.did {$condition} limit 1, 100";

		foreach($db->getAll($sql) as $k => $v) {
			$return[$k] = array(
				'linkurl' => url('company/show', 'id='.$v['did']),
				'id' => $v['did'],
				'company' => $v['title'],
			);
		}

		switch ($type) {
			case self::RETURN_TYPE_JSON;
                echo sprintf('%s(%s);', $_GET['callback'], json_encode($return));
				break;
			case self::RETURN_TYPE_ARRAY:
			default :
				return $return;
		}
	}

	/**
	 * 搜索
	 * @param $kw
	 * @return string
	 */
	public function kwSearch($kw)
	{
        header("content-type: application/x-javascript"); //设置头，否则chrome会失败
		$rule = DT_ROOT . '/file/dict/rules.utf8.ini';
		$dict = DT_ROOT . '/file/dict/car.dict.utf8.xdb';
		$scws = new SCWS(SCWS::CHARSET_UTF8, $rule, $dict);
		$kw   = trim($kw);
		$scws->setText($kw);
		$kws   = $scws->getTops(5);
		$kwsin = array();
		foreach ($kws as $kw) {
			array_push($kwsin, $kw['word']);
		}
		$kwsin   = implode("', '", $kwsin);
		$sql     = "select id from {$this->_tableKw} where keyword in ('{$kwsin}')";
		$results = $this->_db->getCol($sql, 'id');
		$kwidin  = implode(", ", $results);
		$sql     = "select a.*, count(r.aid) as caid from {$this->_tableRel} r, {$this->_table} a where a.id=r.aid AND kwid in ({$kwidin}) group by r.aid order by caid Desc Limit 0, 50";
		$results = $this->_db->getAll($sql);
        echo sprintf('%s(%s);', $_GET['callback'], json_encode($results));
	}

	/**
	 * 获取问题详情
	 * @param $aid
	 * @return mixed
	 */
	public function answer($aid)
	{
        header("content-type: application/x-javascript"); //设置头，否则chrome会失败
		global $db;
		$sql    = "SELECT `content` FROM {$this->_table} WHERE id={$aid}";
		$result = $db->getOne($sql);
		//return $result['content'];
        echo sprintf('%s(%s);', $_GET['callback'], json_encode($result['content']));
	}


	/**
	 * 调用随机问题
	 * @param int    $num
	 * @param string $type
	 * @return array|string
	 */
	public function random($num=13, $type=self::RETURN_TYPE_JSON)
	{
		global $db;
		$num = intval($num);
		$num = $num>50 ? 50 : $num;
		$sql       = "SELECT `id`, `title` FROM {$this->_table} ORDER BY rand()  LIMIT 0, {$num}";
		$questions = $db->getAll($sql);
		if ($type === self::RETURN_TYPE_ARRAY) {
			return $questions;
		} else if ($type === self::RETURN_TYPE_JSON) {
			return json_encode($questions);
		}
	}

	/**
	 * 获取图像生成链接
	 * @param int $clerkid
	 * @return string
	 */
	public function online($clerkid)
	{
		$url = "<img src=\"http://39286.fy.kf.qycn.com/vclient/img.png?websiteid=39286&amp;clerkid=" . $clerkid . "\" onclick=\"window.open('http://39286.fy.kf.qycn.com/vclient/chat/?websiteid=39286&amp;clerkid=" . $clerkid . "&amp;clienturl=http%3A//www.ixdcw.com','_blank', 'toolbar=no,scrollbars=no,menubar=no,status=no,resizable=yes,location=no,width=650,height=500,top=100,left=200')\" style='border:none;cursor:pointer' />";
		return $url;
	}
}